package me.denger.database2Word.service;

import me.denger.database2Word.bean.Column;
import me.denger.database2Word.bean.Table;
import me.denger.database2Word.config.ConfigBean;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * mysql的实现
 *
 * @author 登琼
 */
public class DatabaseImp4Mysql extends DatabaseBaseAbstract {

    public DatabaseImp4Mysql(ConfigBean configBean) throws ClassNotFoundException, SQLException {
        super(configBean);
    }

    public DatabaseImp4Mysql(String driver, String url, String userName, String password)
            throws ClassNotFoundException, SQLException {
        super(driver, url, userName, password);
    }

    @Override
    public List<Table> getTables(String tableNamePrefix) throws SQLException {
        List<Table> tableList = getTableNames(tableNamePrefix);
        for (Table table : tableList) {
            List<Column> columnList = getColumn4Mysql(table.getName());
            table.setColumnList(columnList);
        }
        return tableList;
    }

    /**
     * 获取表中字段的所有注释
     *
     * @param tableName 表名
     * @return 字段列
     */
    private List<Column> getColumn4Mysql(String tableName) {
        List<Column> columnList = new ArrayList<Column>();
        // 与数据库的连接
        try (PreparedStatement statement = getConnection().prepareStatement("show full columns from " + tableName);
             ResultSet rs = statement.executeQuery();) {
            while (rs.next()) {
                Column column = new Column();
                column.setName(rs.getString("FieLd"));
                column.setType(rs.getString("Type"));
                column.setComment(rs.getString("Comment"));
                String key = rs.getString("Key");
                if ("PRI".equals(key)) {
                    column.setKey(true);
                }
                String isNull = rs.getString("Null");
                if ("YES".equals(isNull)) {
                    column.setNullAble(true);
                }
                column.setDefaultValue(rs.getString("Default"));
                columnList.add(column);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return columnList;
    }

}
